<?php
namespace app\shop\model;
use app\common\model\CommonModel;
use app\common\model\ConsultGoods;
use app\common\model\OrderConsult;
use app\common\model\ConsultImg;
use app\common\model\Category;
use think\Session;
use think\Db;

class ConsultModel extends CommonModel
{
	/**
    * 添加商品
    */
    public static function addConGoods($info)
    {
        $Category = new Category();
        $congoods['goods_sn'] = $info['goods_sn'];
        $congoods['goods_name'] = $info['goods_name'];
        $congoods['category_id'] = $info['category_id'];
        $congoods['cat_id'] = $info['cat_id'];
        if($info['category_id'])
        {
            $congoods['category_name'] = $Category->getCategoryField(['category_id'=>$info['category_id']],'category_name');
        }
        if($info['cat_id'])
        {
            $congoods['cat_name'] = $Category->getCategoryField(['category_id'=>$info['cat_id']],'category_name');
        }
        
        if($info['sr_brand_name'])
        {
             $congoods['brand_name'] = $info['sr_brand_name'];
        }else{
             $congoods['brand_name'] = $info['brand_name'];
        }
        $congoods['memory_name'] = $info['memory_name'];
        $congoods['attribute_name'] = $info['attribute_name'];
        $congoods['colour_name'] = $info['colour_name'];
        $congoods['marker'] = $info['marker'];
        $congoods['is_stock'] = $info['is_stock'];
        if(!(new ConsultGoods())->serConsultGoods($congoods))
        {
         return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 获取商品信息
    */
    public static function ConsGoodsList($info)
    {
        $ConsultGoods = new ConsultGoods();
        $where['goods_sn'] = $info['sn'];
        
        $data['data'] = $ConsultGoods->getConsultGoods($where);
        $data['total'] = $ConsultGoods->consGoodsCount($where);
        return $data;
    }
    /**
    * 删除
    */
    public static function delGoods($id)
    {
        if((new ConsultGoods())->delConsultGoods(['consult_goods_id'=>$id]) === false)
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 添加咨询单
    */
    public static function addConsult($info)
    {
        /*开启事物*/
        Db::startTrans();
        /*咨询信息*/
        $ocons['admin_id'] = Session::get('admin.admin_id');
        $ocons['shop_id'] = Session::get('admin.shop_id');
        $ocons['shop_name'] = $info['shop_name'];
        $ocons['clerk'] = $info['clerk'];
        $ocons['user_sn'] = $info['uid'];
        $ocons['username'] = $info['username'];
        $ocons['nkname'] = $info['nkname'];
        $ocons['phone'] = $info['phone'];
        $ocons['spare_phone'] = $info['spare_phone'];
        $ocons['remarks'] = $info['remarks'];
        $ocons['addtime'] = time();
        if(!$ocid = (new OrderConsult())->serOrderConsult($ocons))
        {
            Db::rollback();
            return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO') . 111);
        }
        /*添加咨询商品*/
        $where['consult_goods_id'] = ['IN',$info['gids']];
        $cdata['order_consult_id'] = $ocid;
        $cdata['is_show'] = 1;
        if((new ConsultGoods())->updateConsultGoods($where,$cdata) === false)
        {
            Db::rollback();
            return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO') . 222);
        }
        /*添加图片*/
        $consult = self::base64Upload('upload/consult',$info['imgs']);
        
        $conimg = [];
        foreach($consult as $vo)
        {
            $conimg[] = ['order_consult_id'=>$ocid,'img_src'=>$vo];
        }
        
        if(!(new ConsultImg())->serConsultImg($conimg))
        {
            Db::rollback();
            return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO') . 333);
        }
        Db::commit();
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
	* base64上传
	*/
	private function base64Upload($path,$images)
	{
		header('Content-type:text/html;charset=utf-8');
		$data = [];
		foreach($images as $base64_image_content)
		{
			if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result))
			{
				$type = $result[2];
				$new_file = $path . DS . date('Ymd');
				if(!file_exists($new_file)) 
				{
					/*检查是否有该文件夹，如果没有就创建，并给予最高权限*/
					mkdir($new_file, 0700);
				}
				$new_file = $new_file . DS . 'o' . time() . rand(100,999) . ".{$type}";
				if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content))))
                {
					$data[] = $new_file;
				}else{
					return false;
				}
			}
		}
        return $data;
	}
    /**
    * 获取列表信息
    */
    public static function getConsultList($info)
    {
        $where = self::is_where($info);
        $field = 'o.order_consult_id,o.addtime,o.username,o.phone,o.user_sn,g.goods_name,g.is_stock';
        $data = (new OrderConsult())->getConsultList($where,$field,0,$info['page']);
        foreach($data['data'] as $i=>$vo)
        {
            $data['data'][$i]['addtime'] = date('Y-m-d H:i:s',$vo['addtime']);
            $data['data'][$i]['is_stock'] = $vo['is_stock']==0?'无货':'有货';
        }
        return $data;
    }
    /**
    * 条件整理
    */
	private function is_where($info)
	{
		$where['o.shop_id'] = Session::get('admin.shop_id');
        /*产品属性*/
		if($info['attribute_name'] != '' && $info['attribute_name'])
		{
			$where['g.attribute_name'] = $info['attribute_name'];
		}
        /*产品品牌*/
		if($info['brand_name'] != '' && $info['brand_name'])
		{
			$where['g.brand_name'] = $info['brand_name'];
		}
        /*产品子分类*/
		if($info['cat_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['g.cat_id'] = $info['cat_id'];
		}
        /*产品分类*/
		if($info['category_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['g.category_id'] = $info['category_id'];
		}
        /*产品颜色*/
		if($info['colour_name'] != '' && $info['colour_name'])
		{
			$where['g.colour_name'] = $info['colour_name'];
		}
        /*产品内存*/
		if($info['memory_name'] != '' && $info['memory_name'])
		{
			$where['g.memory_name'] = $info['memory_name'];
		}
        /*关键字搜索*/
		if($info['sreach'])
		{
			$where['g.goods_name'] = ['like','%'.$info['sreach'].'%'];
		}
        /*时间区间*/
        if($info['start'] != '' || $info['end'] != '')
		{
			if($info['start'])
			{
				$where['o.addtime'][] = ['>',strtotime($info['start'])];
			}
			if($info['end'])
			{
				$where['o.addtime'][] = ['<',strtotime($info['end'])];
			}
			return $where;
		}
        /*上月、当前月*/
        if(array_key_exists('shijian',$info))
        {
            if($info['shijian'] != '')
            {
                if($info['shijian'] == CommonModel::NUMBER_ZERO)
                {
                    $where['o.addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
                    $where['o.addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
                }else{
                    $where['o.addtime'][] = ['>',mktime(0, 0, 0,date('m')-1,1,date('Y'))];
                    $where['o.addtime'][] = ['<',mktime(0, 0, 0,date('m'),0,date('Y'))];
                }
            }
        }else{
            $where['o.addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
            $where['o.addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
        }
		return $where;
	}
    /**
    * 咨询详情
    */
    public static function consultInfo($info)
    {
        /*咨询单详情*/
       $getConsultInfo = (new OrderConsult())->getConsultInfo(['order_consult_id'=>$info['id']]);
        /*商品信息*/
       $getConsultGoods = (new ConsultGoods())->getConsultGoods(['order_consult_id'=>$info['id']]);
        /*图片信息*/
        $getConsultImg = (new ConsultImg())->getConsultImg(['order_consult_id'=>$info['id']]);
        return [$getConsultInfo,$getConsultGoods,$getConsultImg];
    }
}
